﻿using LCL.LogNet;
using LCL.Network;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LCL.ModbusTcpServer
{
    public partial class FormModbus : Form
    {
        public FormModbus()
        {
            InitializeComponent();
        }
        private LCL.Network.ModBus.ModbusTcpServer busTcpServer;
        private string timerAddress = string.Empty;
        private ushort timerValue = 0;
        private System.Windows.Forms.Timer timerWrite = null;
        private System.Windows.Forms.Timer timerSecond;
        private void FormModbus_Load(object sender, EventArgs e)
        {
            panel2.Enabled = false;
            comboBox2.SelectedIndex = 0;
            comboBox2.SelectedIndexChanged += ComboBox2_SelectedIndexChanged;
            checkBox3.CheckedChanged += CheckBox3_CheckedChanged;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //启动服务
            int port;
            if (!int.TryParse(textBox2.Text, out port))
            {
                MessageBox.Show("端口输入不正确！");
                return;
            }
            try
            {
                busTcpServer = new LCL.Network.ModBus.ModbusTcpServer();                       // 实例化对象
                busTcpServer.LogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
                busTcpServer.OnDataReceived += BusTcpServer_OnDataReceived;

                ComboBox2_SelectedIndexChanged(null, new EventArgs());
                busTcpServer.IsStringReverse = checkBox3.Checked;
                busTcpServer.ServerStart(port);

                button1.Enabled = false;
                panel2.Enabled = true;
                button4.Enabled = true;
                button11.Enabled = true;

                if (timerSecond != null) timerSecond.Dispose();
                timerSecond = new System.Windows.Forms.Timer();
                timerSecond.Interval = 1000;
                timerSecond.Tick += TimerSecond_Tick;
                timerSecond.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            // 停止服务
            busTcpServer.ServerClose();
            button1.Enabled = true;
            button11.Enabled = false;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //客户端过滤
            if (busTcpServer == null)
            {
                MessageBox.Show("必须先启动服务器！");
                return;
            }
            // 信任客户端配置
            using (FormTrustedClient form = new FormTrustedClient(busTcpServer))
            {
                form.ShowDialog();
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //启动串口
            if (busTcpServer != null)
            {
                try
                {
                    busTcpServer.StartSerialPort(textBox10.Text);
                    button5.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("串口服务器启动失败：" + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("请先启动Tcp服务器：");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //连接异形客户端
            using (FormInputAlien form = new FormInputAlien())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Result connect = busTcpServer.ConnectHslAlientClient(form.IpAddress, form.Port, form.DTU);
                    if (connect.Success)
                    {
                        MessageBox.Show("连接成功！");
                    }
                    else
                    {
                        MessageBox.Show("连接失败！原因：" + connect.Message);
                    }
                }
            }
        }


        private void LogNet_BeforeSaveToFile(object sender, LogNet.LogEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, LogNet.LogEventArgs>(LogNet_BeforeSaveToFile), sender, e);
                return;
            }
            textBox1.AppendText(e.HslMessage.ToString() + Environment.NewLine);
        }
        private void BusTcpServer_OnDataReceived(LCL.Network.ModBus.ModbusTcpServer tcpServer, byte[] modbus)
        {
            if (!checkBox1.Checked) return;

            if (InvokeRequired)
            {
                BeginInvoke(new Action<LCL.Network.ModBus.ModbusTcpServer, byte[]>(BusTcpServer_OnDataReceived), tcpServer, modbus);
                return;
            }
            textBox1.AppendText("接收数据：" + Utils.ByteToHexString(modbus, ' ') + Environment.NewLine);
        }
        private void TimerSecond_Tick(object sender, EventArgs e)
        {
            label15.Text = busTcpServer.OnlineCount.ToString();
        }
        private void ComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (busTcpServer != null)
            {
                switch (comboBox2.SelectedIndex)
                {
                    case 0: busTcpServer.DataFormat = DataFormat.ABCD; break;
                    case 1: busTcpServer.DataFormat = DataFormat.BADC; break;
                    case 2: busTcpServer.DataFormat = DataFormat.CDAB; break;
                    case 3: busTcpServer.DataFormat = DataFormat.DCBA; break;
                    default: break;
                }
            }
        }
        private void CheckBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (busTcpServer != null)
            {
                busTcpServer.IsStringReverse = checkBox3.Checked;
            }
        }
    }
}
